package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type User struct {
	Ctx iris.Context
}

type UserListParam struct {
	UserType int    `json:"userType"`
	Name     string `json:"name"`
	Phone    string `json:"phone"`
	PerPage  int    `json:"perPage"`
	CurPage  int    `json:"curPage"`
}

func (c *User) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *User) PostList() interface{} {
	userListParam := UserListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错：%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &userListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错：%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	start := (userListParam.CurPage - 1) * userListParam.PerPage
	userList := make([]models.User, 0)
	sess := db.Limit(userListParam.PerPage, start)
	if userListParam.UserType > 0 {
		sess = sess.Where("user_type = ?", userListParam.UserType)
	}
	if len(userListParam.Name) > 0 {
		sess = sess.Where("name like ?", fmt.Sprintf("%%%s%%", userListParam.Name))
	}
	if len(userListParam.Phone) > 0 {
		sess = sess.Where("phone like ?", fmt.Sprintf("%%%s%%", userListParam.Phone))
	}
	err = sess.Find(&userList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取会员列表:%s", err.Error()), "")
	}

	countSess := db.Where("id > ?", 0)
	if userListParam.UserType > 0 {
		countSess = countSess.Where("user_type = ?", userListParam.UserType)
	}
	if len(userListParam.Name) > 0 {
		countSess = countSess.Where("name like ?", fmt.Sprintf("%%%s%%", userListParam.Name))
	}
	if len(userListParam.Phone) > 0 {
		countSess = countSess.Where("phone like ?", fmt.Sprintf("%%%s%%", userListParam.Phone))
	}
	total, err := countSess.Count(new(models.User))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取会员列表:%s", err.Error()), "")
	}

	for i, item := range userList {
		userList[i].SubjectShow = models.RankSubject[item.Subject]
		userList[i].UserTypeShow = models.UserType[item.UserType]
		userList[i].ChannelShow = models.UserChannel[item.Channel]
		userList[i].ModeShow = models.UserMode[item.Mode]
		userList[i].UserCreated = item.Created.Format("2006-01-02 15:04")
	}

	data := map[string]interface{}{
		"total": total,
		"list":  userList,
	}

	return utils.CommonRes(20000, "成功获取会员列表", data)
}
